import {
  addAdminApi,
  delAdminApi,
  editAdminInfoApi,
  getAdminList,
} from '../services/admin';

export default {
  namespace: 'admin',
  state: {
    adminList: [],
    adminInfo: {},
    test: '测试链接',
  },
  effects: {
    *_initList(_, { put, call }) {
      const data = yield call(getAdminList);
      // console.log(data);

      yield put({
        type: 'initList',
        payload: data.data,
      });
    },
    *_editListInfo(action, { put, call }) {
      const { payload } = action;
      const resp = yield call(editAdminInfoApi, payload.id, payload.data);
      // console.log(resp, '结果');
      // 更改仓库数据
      yield put({
        type: 'editListInfo',
        payload,
      });
    },
    *_addAdmin(action, { put, call }) {
      const { payload } = action;
      const resp = yield call(addAdminApi, payload);
      //  console.log("新增结果",resp)
      yield put({
        type: 'addAdmin',
        payload: resp.data,
      });
    },
    *_delAdmin(action, { put, call }) {
      const { payload } = action;
      console.log(payload);
      yield call(delAdminApi, payload);
      yield put({
        type: 'delAdmin',
        payload: payload,
      });
    },
  },
  reducers: {
    initList(state, action) {
      const newState = { ...state };
      newState.adminList = action.payload;
      return newState;
    },
    editListInfo(state, action) {
      // console.log(action.payload, '这里看一下');
      const { payload } = action;
      const newState = { ...state };
      const tempArr = [...newState.adminList];
      // 找到需要修改的
      const tarArr = tempArr.map((item) => {
        if (item._id === payload.id) {
          //目标
          return Object.assign({}, item, payload.data);
        } else {
          return { ...item };
        }
      });
      newState.adminList = tarArr;
      return newState;
    },
    addAdmin(state, action) {
      const { payload } = action;
      // 新增一个管理员
      const newState = { ...state };
      const tempArr = [...newState.adminList];
      tempArr.push(payload);
      newState.adminList = tempArr;
      return newState;
    },
    delAdmin(state, action) {
      const { payload } = action;
      // 拿到要删除的id
      const newState = { ...state };
      const tempArr = [...newState.adminList];
      const tarArr = tempArr.filter((item) => {
        return item._id !== payload;
      });
      newState.adminList = tarArr;
      return newState;
    },
  },
};
